<template>
  <div ref="ele" class="single-view" v-show="show">
      
  </div>
</template>

<script>
/* eslint-disable */
import echarts from "echarts";
import Debug from "debug";
import _ from "lodash";
import util from "util";
import axios from "axios";
import color from "color";
import { equal } from "assert";

const dbg = Debug("SingleView.vue");
dbg.enabled = true;

export default {
  data() {
    return {
      chart: echarts.init(document.createElement("null")),
      channel: ""
    };
  },
  props: {
    showindex: {
      type: Number,
      default: 3
    },
    trendData: {
      type: Object
    },
    testIdLines: {
      type: Object
    },
    raw: {
      type: Object
    },
    channel2GoodText: {
      type: Function
    },
    channel2danwei: {
      type: Function
    },
    count_in_selection: {
      type: Number
    }
  },
  computed: {
    show() {
      return this.showindex === 0;
    },
    trendDataString() {
      // return util.inspect(this.trendData);
      return JSON.stringify(this.trendData);
    },
    /**@return {Object}
     */
    abnormal_type2color() {
      return this.$store.state.abnormal_type2color;
    },
    colorByType() {
      return type => this.abnormal_type2color[this.abnormal_type2comment[type]];
    },
    colorChangeLightness() {
      return (hexColor, L) => {
        let c = color(hexColor);
        // debugger;
        let hslc = c.hsl();
        hslc = hslc.lightness(L);
        // debugger
        return hslc.hex();
      };
    },
    abnormal_type2comment() {
      return this.$store.getters["abnormal_type2comment"];
    },
    starterId() {
      return this.$store.state.starterId;
    },
    channel2max() {
      return this.$store.state.feature_channel_2_max;
    },
    gray_colors() {
      return this.$store.state["gray_colors"];
    },
    font_size() {
      return this.$store.getters["axis_font_size"];
    },
    channel2yAxisName() {
      return this.$store.state["channel2yAxisName"];
    },
    /**@returns {Number} */
    OFFSET: function() {
      let trendData = this.trendData;

      let channel = this.channel;
      if (!channel) {
        return 0;
      }
      let mapped = _.filter(
        _.map(trendData, e => (e ? (e[channel] ? e[channel] : null) : null))
      );
      // debugger
      if (mapped.length == 0) {
        return 0;
      }
      let mapped_mins = mapped.map(e => e["min"]);
      let min_value = _.min(_.flatten(mapped_mins));
      if (min_value < 0) {
        return Math.ceil(0 - min_value);
      } else {
        return 0;
      }
    },
    opt_yAxis() {
      return {
        axisLabel: {
          formatter: (value, index) => {
            let v = value - this.OFFSET;
            v = String(v);
            let i = v.indexOf(".");

            if (i != -1) {
              if (v.substring(i).length >= 3) {
                v = Number(v).toFixed(2);
              }
            }
            return v;
          },
          color: this.gray_colors[1],
          fontSize: this.font_size + 1
        },
        axisLine: {
          lineStyle: {
            color: this.gray_colors[0]
          }
        },
        min: 0 + this.OFFSET,
        // max: this.channel2max[this.channel] + this.OFFSET,
        name: this.channel2GoodText(
          this.channel ||
            (_.isString(this.channel)
              ? this.channel.toUpperCase()
              : this.channel)
        ),
        nameGap: 40,
        nameRotate: 90,
        nameLocation: "center",
        nameTextStyle: {
          color: this.gray_colors[1],
          fontSize: this.font_size + 1
        },
        splitArea: {
          show: false
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: this.gray_colors[0],
            type: "dotted",
            opacity: 0.5
          }
        }
      };
    },
    /**@description 关于趋势的series */
    opt_serieses() {
      let filtered = _.filter(this.trendData);
      if (filtered.length && filtered[0][this.channel]) {
        let mapValues_ed = _.mapValues(this.trendData, (channels, type) => {
          if (!channels) return null;
          let channel = this.channel;
          // debugger;
          let channel_data = channels[channel];
          let data = channel_data.data.map(row =>
            row.map(d => d + this.OFFSET)
          );
          // debugger;
          return [
            {
              //min
              name: `${this.abnormal_type2comment[type]}`,
              type: "line",
              data: channel_data.index.map((d, i) => {
                return [d, data[i][0].toFixed(2)];
              }),
              itemStyle: {
                color: this.colorByType(type)
              },
              lineStyle: {
                normal: {
                  color: this.colorByType(type),
                  opacity: 0.1,
                  type: "dotted"
                }
              },
              stack: `bound(${type})`,
              smooth: true,
              symbol: "none",
              showSymbol: false
            },
            {
              // 25%
              name: `${this.abnormal_type2comment[type]}`,
              type: "line",
              data: channel_data["index"].map((d, i) => {
                return [d, data[i][1].toFixed(2)];
              }),
              itemStyle: {
                color: this.colorByType(type)
              },
              lineStyle: {
                normal: {
                  color: this.colorByType(type),
                  opacity: 0
                }
              },
              // areaStyle:{
              //   opacity:0.3
              // },
              stack: `main(${type})`,
              smooth: true,
              symbol: "none",
              showSymbol: false
            },
            {
              // 50%
              name: `${this.abnormal_type2comment[type]}`,
              type: "line",
              data: channel_data["index"].map((d, i) => {
                return [d, data[i][2].toFixed(2)];
              }),
              itemStyle: {
                color: this.colorByType(type)
              },
              lineStyle: {
                // type: "dashed",
                color: this.colorChangeLightness(this.colorByType(type), 45),
                opacity: 0.5
              },
              xAxisIndex: 0,
              smooth: true,
              symbol: "none",
              showSymbol: false
            },
            {
              //75%
              name: `${this.abnormal_type2comment[type]}`,
              type: "line",
              data: channel_data["index"].map((d, i) => {
                return [d, (data[i][3] - data[i][1]).toFixed(2)];
              }),
              lineStyle: {
                normal: {
                  color: this.colorByType(type),
                  opacity: 0
                }
              },
              itemStyle: {
                color: this.colorByType(type)
              },
              areaStyle: {
                color: this.colorChangeLightness(this.colorByType(type), 65),
                opacity: 0.4
              },
              stack: `main(${type})`,
              smooth: true,
              symbol: "none",
              showSymbol: false
            },
            {
              //max
              name: `${this.abnormal_type2comment[type]}`,
              type: "line",
              data: channel_data.index.map((d, i) => {
                return [d, (data[i][4] - data[i][0]).toFixed(2)];
              }),
              itemStyle: {
                color: this.colorByType(type)
              },
              lineStyle: {
                normal: {
                  color: this.colorByType(type),
                  opacity: 0.1,
                  type: "dotted"
                }
              },
              areaStyle: {
                color: this.colorChangeLightness(this.colorByType(type), 90),
                opacity: 0.5
              },
              stack: `bound(${type})`,
              smooth: true,
              symbol: "none",
              showSymbol: false
            }
          ];
        });
        mapValues_ed = _.map(mapValues_ed, (val, key) => {
          return { val, key };
        });
        mapValues_ed = mapValues_ed.sort((A, B) => {
          if (A && B) {
            let [nameA, nameB] = [
              this.abnormal_type2comment[A["key"]],
              this.abnormal_type2comment[B["key"]]
            ].map(e => e + "");
            let [AisTypical, BisTypical] = [nameA, nameB].map(e =>
              e.startsWith("C")
            );
            // debugger
            if (AisTypical && BisTypical) return nameA.localeCompare(nameB);
            if (AisTypical && !BisTypical) return -1;
            if (!AisTypical && BisTypical) return 1;
            return nameA.localeCompare(nameB);
          }
          return A - B;
        });
        mapValues_ed = mapValues_ed.map(e => e["val"]);
        let trends = _.filter(_.flatten(_.map(mapValues_ed)));
        // trends = _.shuffle(trends);
        return trends;
      } else {
        //温度的趋势暂时没搞好
        return [];
      }
    },
    opt_lines() {
      let arr = [];
      for (let testid in this.testIdLines) {
        let data_parent = this.testIdLines[testid]["channel_data"].find(
          e => e["channel"] == this.channel
        );
        if (data_parent) {
          let data = data_parent["data"].map((e, i) => [i, e + this.OFFSET]);
          arr.push({
            type: "line",
            name: `line`,
            data: data,
            lineStyle: {
              type: "solid",
              color: "#ff80ff",
              opacity: 0.6
            },
            itemStyle: {
              color: "#ff80ff"
            },
            markPoint: {
              // symbol:"arrow",
              data: [
                {
                  // name:testid,
                  value: `${testid}`,
                  coord: _.maxBy(data, d => d[1])
                }
              ],
              label: {
                fontSize: 10
              },
              itemStyle: {
                color: "rgba(255,0,0,0.3)"
              }
            }
          });
        }
      }
      return arr;
    },
    opt_fake_raw() {
      if (this.opt_serieses.length) {
        return [
          {
            type: "line",
            name: "date"
          }
        ];
      } else {
        return [];
      }
    },
    opt_legend() {
      let vue = this;
      return {
        data: [
          ...this.opt_serieses.map(e => {
            return {
              name: e["name"],
              icon:
                "path://M 0 0.15 L 1 0.15 L 1 0.85  L 0 0.85 L 0 0 z M 0 0.4 L -0.3 0.4 L -0.3 0.6 L 0 0.6 z M 1 0.4 L 1.3 0.4 L 1.3 0.6 L 1 0.6 z "
            };
          }),
          "line",
          { name: "date", icon: "none" }
        ],
        top: 10,
        itemWidth: 30,
        itemHeight: 14,
        left: "center",
        formatter: function(name) {
          if (name == "date") {
            if (!vue.raw.dates.length) return "";
            return `[${vue.raw.dates[0]} ~ ${
              vue.raw.dates[vue.raw.dates.length - 1]
            } , ${vue.$_getCountInSelection()} tests]`;
          } else {
            if (name.startsWith("C")) {
              name = name.replace("C", "T");
            }
            return name;
          }
        }
      };
    },
    opt_echarts() {
      let vue = this;
      return {
        backgroundColor: "white",
        grid: {
          left: 70,
          right: 100,
          top: 45,
          bottom: 60,
          show: false
        },
        legend: this.opt_legend,
        xAxis: {
          type: "category",
          data: _.range(0, 2001),
          axisLine: {
            onZero: false,
            lineStyle: {
              fontSize: 12,
              color: this.gray_colors[0]
            }
          },
          name: "Tune (ms)",
          nameGap: 34,
          nameLocation: "center",
          nameTextStyle: {
            color: this.gray_colors[1],
            textShadowColor: "transparent",
            textShadowBlur: 0,
            textShadowOffsetY: 14,
            fontSize: this.font_size + 1
          },
          axisLabel: {
            color: this.gray_colors[1],
            fontSize: this.font_size + 1,
            interval: (index, value) => {
              return value % 250 == 0;
            }
          },
          axisTick: {
            alignWithLabel: true,
            interval: (index, value) => {
              return value % 250 == 0;
            }
          }
        },
        yAxis: this.opt_yAxis,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // type: "cross"
          },
          formatter: function(params, a, b) {
            let findTypeidByTypenametext = str => {
              for (let id in vue.abnormal_type2comment) {
                if (vue.abnormal_type2comment[id] == str) {
                  return id;
                }
              }
              return null;
            };
            if (params.length) {
              let uniq_params = _.uniqBy(params, e => e["seriesName"]);
              let texts = uniq_params
                .map(param => {
                  let tune = param["data"][0];
                  let dataIndex = param["dataIndex"];
                  let typename = param["seriesName"];
                  let typeid = findTypeidByTypenametext(typename);
                  if (!typeid) {
                    return "";
                  }
                  try {
                    let [min, q1, q2, q3, max] = [
                      vue.trendData[typeid][vue.channel]["data"][dataIndex][0],
                      vue.trendData[typeid][vue.channel]["data"][dataIndex][1],
                      vue.trendData[typeid][vue.channel]["data"][dataIndex][2],
                      vue.trendData[typeid][vue.channel]["data"][dataIndex][3],
                      vue.trendData[typeid][vue.channel]["data"][dataIndex][4]
                    ].map(e => {
                      // let s = String(e);
                      // let i = s.indexOf(".");
                      /**@description 精确到小数点后三位 */
                      return Math.round(e * 1000) / 1000;
                    });

                    /**@description 记得把C1C2改成T1T2 */
                    if (typename.startsWith("C")) {
                      typename = typename.replace("C", "T");
                    }

                    return `Mode : ${typename}<br> Tune : ${tune} ms<br>
                    max : ${max}  ${vue.channel2danwei(vue.channel)}<br>
                    q3 : ${q3}  ${vue.channel2danwei(vue.channel)}<br>
                    q2 : ${q2}  ${vue.channel2danwei(vue.channel)}<br>
                    q1 : ${q1}  ${vue.channel2danwei(vue.channel)}<br>
                    min : ${min}  ${vue.channel2danwei(vue.channel)}<br> 
                  `;
                  } catch (e) {
                    return "";
                  }
                })
                .filter(e => !!e);
              return `Channel : ${vue.channel2GoodText(
                vue.channel
              )} <br>${texts.join("<br>")}`;
            }
          }
        },
        graphic: {
          elements: [
            {
              type: "text",
              right: 100,
              top: 45,
              style: {
                text: this.channel2GoodText(this.channel),
                font: `bolder 2.5em "Microsoft YaHei", sans-serif`,
                fill: "#e2e2e2"
              },
              cursor: "default"
            }
          ]
        },
        series: _.sortBy(
          [...this.opt_serieses, ...this.opt_lines, ...this.opt_fake_raw],
          e => e.name
        )
        // brush: {
        //   toolbox: ["rect", "clear"],
        //   throttleDelay: 1000,
        //   throttleType: "debounce",
        //   xAxisIndex: 0,
        //   yAxisIndex: 0
        // }
      };
    }
  },
  mounted() {
    let chart = (this.chart = echarts.init(this.$refs["ele"]));
    let vue = this;
    chart.setOption(this.opt_echarts);
    // chart.on("brushselected", function(params) {
    //   if (params.batch.length && params.batch[0].areas.length) {
    //     let area = params.batch[0].areas[0];
    //     let xCoordRange = area.coordRange[0];
    //     let yCoordRange = area.coordRange[1];
    //     vue.$_queryTestidsInRect(xCoordRange, yCoordRange);
    //   }
    // });
  },
  methods: {
    /**@api public
     @param {"speed"|"i50"|"i30"|"u30"|"u45"|"u50"} channel*/
    setChannel(channel) {
      this.channel = channel;
    },
    $_getCountInSelection() {
      return this.count_in_selection;
    },
    $_draw() {
      this.chart.clear();
      this.chart.setOption(this.opt_echarts);
    },
    $_queryTestidsInRect(xRange, yRange) {
      // dbg("%j",{xRange,yRange});
      let xs = [Math.floor(xRange[0]), Math.ceil(xRange[1])];
      let ys = [
        Math.floor(yRange[0] - this.OFFSET),
        Math.ceil(yRange[1] - this.OFFSET)
      ];
      let brushed_dates = this.$store.state.brushed_dates;
      let brushed_types = this.$store.state.brushed_types;
      dbg("%j", { xs, ys, brushed_dates, brushed_types });
      axios.get("/starter/overview/selection/brushed/", {
        params: {
          starterId: this.starterId,
          xs: xs,
          ys: ys,
          channel: this.channel
        }
      });
    }
  },
  watch: {
    trendDataString(val, old) {
      // dbg("trendDataString", { val, old });
    },
    opt_echarts(val) {
      this.$_draw();
    },
    show(val) {
      if (val) {
        // dbg("show...drawing.....");
        // this.$_draw();
      }
    }
  }
};
</script>

<style lang="less">
.single-view {
  background-color: white;
  width: 1326px;
  height: 708px;
}
</style>
